<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>WebSocket ADC Demo</title>
    <link href="layout.css" rel="stylesheet" type="text/css">
    <script language="javascript" type="text/javascript" src="/jquery/1.8.1/jquery.min.js"></script>
    <script language="javascript" type="text/javascript" src="/jquery/flot/jquery.flot.js"></script>
 </head>
    <body>
    <h1>WebSocket ADC Monitor</h1>

    <div id="placeholder" style="width:600px;height:300px;"></div>

<script type="text/javascript">
$(function () {
    // we use an inline data source in the example, usually data would
    // be fetched from a server
    var MAX_ADC_VALUE = 4095;
    var MAX_AD_SAMPLES = 50;
    var TOTAL_POINTS = 300;

    // setup plot
    var options = {
        series: { shadowSize: 0 }, // drawing is faster without shadows
        yaxis: { min: 0, max: MAX_ADC_VALUE },
        xaxis: { show: false }
    };

    var data = [];
    function initData() {
        var i;
        // create data array
        for (i=0; i<=TOTAL_POINTS; i++) {
            data.push(0);    
        }
        // update draw data
        var res = []
        for (var i=0; i<TOTAL_POINTS; ++i) 
            res.push([i, data[i]]);
        return res;        
    }

    var plot = $.plot($("#placeholder"), [ initData() ], options);

    // update by WebSocket
    if (window["WebSocket"]) {
    	var host = window.location.hostname;
        var socket = new WebSocket("ws://" + host + "/adc");
        socket.onmessage = function(evt) {
            var msg = JSON.parse(evt.data);
            var i,start;

            // shift data
            data = data.slice(MAX_AD_SAMPLES);
            start = TOTAL_POINTS-MAX_AD_SAMPLES;

            // update data by JSON value
            for (i=0; i<MAX_AD_SAMPLES; i++ ) {
                data[start+i] = msg.value[i];
            }

            // create draw data
            var res = [];
            for (i=0; i<TOTAL_POINTS; i++) {
                res.push([i,data[i]]);    
            }

            // draw all data
            plot.setData([res]);
            plot.draw();
        }
    } 
});
</script>

 </body>
</html>